const axios = require('axios')

const getTemplate = () => {
  return new Promise((resolve, reject) => {
    axios.get('http://localhost:8787/public/server.ejs')
      .then((res) => {
        resolve(res.data)
      })
      .catch(reject)
  })
};

const serverConfig = require('../../build/webpack.config.server')
const webpack = require('webpack')
const path = require('path')
const MemoryFs = require('memory-fs')

const Module = module.constructor

const mfs = new MemoryFs
const serverCompiler = webpack(serverConfig)
serverCompiler.outputFileSystem = mfs

let serverBundle
serverCompiler.watch({}, (err, stats) => {
  if (err) throw err
  stats = stats.toJson()
  stats.errors.forEach(err => console.error(err))
  stats.warnings.forEach(warn => console.warn(warn))

  const bundlePath = path.join(serverConfig.output.path, serverConfig.output.filename)
  const serverBundleString = mfs.readFileSync(bundlePath, 'utf-8')

  const m = new Module()
  m._compile(serverBundleString, 'server-entry.js')
  serverBundle = m.exports
});

const renderServer = require('./server-render')
module.exports = function(app) {
  const proxy = require('http-proxy-middleware')
  app.use('/public', proxy({target: 'http://localhost:8787'}))
  app.get('*', function(req, res) {
    if (!serverBundle) {
      return res.send('waiting for compile, refresh later')
    }
    getTemplate().then((template) => {
      console.log('准备执行server render')
      return renderServer(serverBundle, template, req, res)
    })
  })
};
